using Game.Networking;
using NaughtyAttributes;
using System.Collections.Generic;
using UnityEngine;

namespace Game {
	public sealed partial class SecurityTurret : WorldEntity<SecurityTurretState> {
		public float ScanRadius        = 25;
		public float DisengageDistance = 30;
		public float UpdateInterval    = 0.05f;

		public List<TurretGun> Guns = new List<TurretGun>();
		public ShipPhysics ShipPhysics;

		public override EntityType EntityType => EntityType.SecurityTurret;

		SecurityTurretState _state = new SecurityTurretState();
		Collider[] _tmpColliderArray = new Collider[32];
		ShipCore _target;
		float _lastUpdateTime = 0f;

		[ShowNativeProperty]
		public TeamType Team {
			get {
				return _state.Team;
			}
			set {
				_state.Team = value;
				GetComponentInChildren<TeamSkin>()?.SetTeamColor(value);
			}
		}

		public override void Create() {
			base.Create();
			if ( !IsServer ) {
				ShipPhysics.enabled = false;
			}
		}

		public override void Tick(float currentTime, float deltaTime) {
			base.Tick(currentTime, deltaTime);
			if ( !IsServer) {
				return;
			}
			if ( currentTime - _lastUpdateTime < UpdateInterval ) {
				return;
			}
			_lastUpdateTime = currentTime;
			if ( _target ) {
				if ( Vector3.Distance(_target.transform.position, transform.position) > DisengageDistance ) {
					_target = null;
				} else {
					ShipPhysics.MoveTarget = _target.transform.position;
					if ( IsLookingAtTarget() ) {
						S_CallRPC_ShootGuns(true);
					}
				}
			}
			FindTarget();
		}

		[ClientRPC(16)]
		void ShootGuns() {
			if ( Random.value > 0.5f) {
				Guns[0].Shoot();
			} else {
				Guns[1].Shoot();
			}
		}

		public bool IsLookingAtTarget() {
			var toTarget = (ShipPhysics.MoveTarget - transform.position).normalized;
			var forward = transform.TransformDirection(Vector3.forward);
			if ( Vector3.Dot(toTarget, forward) > 0.9f ) {
				return true;
			}
			return false;
		}

		void FindTarget() {
			var count = Physics.OverlapSphereNonAlloc(transform.position, ScanRadius, _tmpColliderArray, CommonStaticData.Instance.DynamicEntitiesMask, QueryTriggerInteraction.Ignore);
			for ( int i = 0; i < count; i++ ) {
				var entity = _tmpColliderArray[i].GetComponent<Entity>();
				if ( !entity ) {
					continue;
				}
				if ( entity.EntityType == EntityType.Ship ) {
					var ship = (ShipCore)entity;
					if ( ship == null ) {
						continue;
					}
					if ( CommonStaticData.IsHostileTeam(Team, ship.Team) ) {
						_target = ship;
						break;
					}
				}
			}
		}

		public override void ApplyFullState(EntityState state) {
			base.ApplyFullState(state);
			var cast = (SecurityTurretState)state;
			if ( cast == null ) {
				return;
			}
			Team = cast.Team;
		}

		protected override SecurityTurretState SaveInternal() {
			var s = base.SaveInternal();
			s.Team = _state.Team;
			return s;
		}

		protected override string CreateSummary() {
			return $"type:turret,team:{Team}";
		}
	}
}

